// pages/detail/detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:"",
    pic:null,
    name:"",
    count:1,
    price:0
  },
  //减少
reduce(){
  const count = this.data.count > 1? parseInt(this.data.count) - 1 :1
  this.setData({
    count
  })
},
//增加
add(){
  const count = this.data.count < 20?parseInt(this.data.count)  + 1 : 20
  this.setData({
    count
  })
},
//直接输入数字
countInput(e){
  let count = e.detail.value
  const regNum = new RegExp(/^[0-9]*$/)
  const result = regNum.exec(count)
  if(result == null || count < 0){
    count = 0
  }else if(count > 21){
    count = 20
  }
  this.setData({
    count
  })
},
addCart(){
  const data = {
    id:this.data.id,
    name:this.data.name,
    count:this.data.count,
    pic:this.data.pic,
    price:this.data.price
  }
  const app = getApp()
  const cart = app.globalData.cart
  let num = 0
    cart.map(i=>{
      num += i.count
    })
    if(num >= 20){
      return false
    }
  if (cart.some(i => i.id == data.id)) {
    const index = cart.findIndex(i => i.id == data.id)
    cart[index].count = data.count
  } else {
    cart.push(data)
  }
wx.navigateTo({
  url: `/pages/cart/cart`
})
},
goBack(){
  wx.navigateBack({
    complete: (res) => {},
    delta: 0,
    fail: (res) => {},
    success: (res) => {},
  })
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id:options.id,
      pic:options.pic,
      name:options.name,
      count:options.count == 0?1:options.count,
      price:parseInt(options.price)
    })
   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})